#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "button.h"
#include "xl9555.h"

#define XL9555_SDA  GPIO_NUM_10
#define XL9555_SCL  GPIO_NUM_11

#define TAG     "main"

//按位表示
static volatile uint16_t xl9555_button_level = 0xFFFF;

int get_button_level(int gpio)
{
    return (xl9555_button_level&gpio)?1:0;
}

void xl9555_input_callback(uint16_t io_num,int level)
{
    if(level)
    {
        xl9555_button_level |= io_num;
    }
    else
    {
        xl9555_button_level &= ~io_num;
    }
}

void short_press(int gpio)
{
    ESP_LOGI(TAG,"Button %d short press",gpio);
}

void long_press(int gpio)
{
    ESP_LOGI(TAG,"Button %d long press",gpio);
}

void button_init(void)
{
    button_config_t button_cfg = 
    {
        .active_level = 0,
        .getlevel_cb = get_button_level,
        .gpio_num = IO0_1,
        .long_cb = long_press,
        .long_press_time = 3000,
        .short_cb = short_press,
    };
    button_event_set(&button_cfg);
    button_cfg.gpio_num = IO0_2;
    button_event_set(&button_cfg);
    button_cfg.gpio_num = IO0_3;
    button_event_set(&button_cfg);
    button_cfg.gpio_num = IO0_4;
    button_event_set(&button_cfg);
}

void i2c_and_xl9555_init(void)
{
    xl9555_init(XL9555_SDA,XL9555_SCL,GPIO_NUM_17,xl9555_input_callback);
    xl9555_ioconfig(0xFFFF);
}

void app_main(void)
{
    i2c_and_xl9555_init();
    button_init();
}
